package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.enums.GlobalErrorCodeEnum;
import com.example.lotterysystem.common.exception.GlobalException;
import com.example.lotterysystem.common.utils.*;
import com.example.lotterysystem.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SMSUtil smsUtil;

    private static final String TEMPLATE_CODE = "SMS_473885198";
    private static final String VERIFY_CODE = "VERIFY_CODE_";
    private static final Long TTL = 300L;

    @Override
    public void sendVerifyCode(String phoneNumber) {
        // 1. 校验手机号
        if(!RegexUtil.checkPhoneNumber(phoneNumber)) {
            throw new GlobalException("发送验证码失败: 手机号格式有误");
        }

        // 2. 生成随机验证码
        String verifyCode = CaptchaUtil.getCaptcha(6);

        // 3. 发送验证码
        // {"code" : "xxx"}
        Map<String, String> map = new HashMap<>();
        map.put("code", verifyCode);
        smsUtil.sendMessage(TEMPLATE_CODE, phoneNumber, JacksonUtil.writeValueAsString(map));

        // 4. 缓存验证码
        redisUtil.set(VERIFY_CODE + phoneNumber, verifyCode, TTL);
    }

    @Override
    public String getVerifyCode(String phoneNumber) {
        // 1. 校验手机号
        if(!RegexUtil.checkPhoneNumber(phoneNumber)) {
            throw new GlobalException(GlobalErrorCodeEnum.LOGIN_ERROR, "手机号格式有误");
        }

        // 2. 获取验证码
        return redisUtil.get(VERIFY_CODE + phoneNumber);
    }
}
